package priv.yiyuan.example.design.proxy;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 缓存和日志
 * <p>
 * CGLIB 动态代理拦截器
 *
 * @author YiYuan
 * @data 2025/9/24
 * @apoNote
 */
public class CacheAndLogMethodInterceptor implements MethodInterceptor {

    private Object target;

    private Map<String, Object> cache = new HashMap<>();

    public CacheAndLogMethodInterceptor(Object target) {
        this.target = target;
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {

        System.out.println("\n--- CGLIB 代理前置处理: 方法 " + method.getName() + " 被调用, 参数: " + Arrays.toString(args) + " ---");

        if (method.getName().equals("getConfig") && args.length == 1 && args[0] instanceof String) {
            String key = (String) args[0];
            if (cache.containsKey(key)) {
                System.out.println("CGLIB 代理: 从缓存中获取配置项: " + key);
                return cache.get(key);
            }
        }

        Object result = null;

        try {
            result = proxy.invokeSuper(obj, args);

            if (method.getName().equals("getConfig") && args.length == 1 && args[0] instanceof String && result != null) {
                String key = (String) args[0];
                cache.put(key, result);
                System.out.println("CGLIB 代理: 将配置项 " + key + " 放入缓存。");
            }

        } catch (Exception e) {
            System.out.println("CGLIB 代理异常处理: 方法 " + method.getName() + " 执行异常: " + e.getMessage());

            throw e.getCause();

        } finally {
            System.out.println("--- CGLIB 代理后置处理: 方法 " + method.getName() + " 执行完毕。---");
        }

        return result;
    }

}
